package com.landun.market.pojo.enums;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author jiang.chuan
 * @date 2018-05-05
 */
public enum ResponseCode {

    SUCCESS(200, "成功"),

    // 全局错误
    SYSTEM_ERROR(-1, "系统异常"),
    BUSINESS_ERROR(-2, "业务异常", "(%s)业务发生异常"),
    UNKNOWN_ERROR(-3, "未知错误"),

    // 用户认证
    UNAUTHORIZED(101, "用户未授权", "[%s]用户未授权"),
    LOGIN_FAILED(102, "登录失败", "[%s]登录失败"),
    USER_EXPIRED(103, "用户已失效", "[%s]用户已失效"),
    PERMISSION_DENIED(104, "无权查询数据", "[%s]无权查询数据"),

    // 参数校验
    PARAMETER_REQUIRED(111, "参数必传", "[%s]参数不能不空"),
    PARAMETER_FORMAT_ERROR(112, "参数格式错误", "[%s]参数格式不正确"),
    DATA_EXISTED(113, "数据已经存在", "[%s-%s]数据已经存在"),

    // 增删改查
    CREATE_FAILED(201, "增加失败", "增加[%s]失败"),
    UPDATE_FAILED(202, "修改失败", "修改[%s-%s]失败"),
    DELETE_FAILED(203, "删除失败", "删除[%s-%s]失败"),
    DISABLE_FAILED(204, "禁用失败", "禁用[%s-%s]失败"),
    ENABLE_FAILED(205, "启用失败", "启用[%s-%s]失败"),
    AUDIT_FAILED(206, "审核失败", "审核[%s-%s]失败"),
    REARRANGE_FAILED(207, "重新排序失败", "重新排序[%s]失败"),

    DATA_NOT_CREATED(211, "数据未写入", "数据[%s]未写入"),
    DATA_NOT_UPDATED(212, "数据未更新", "数据[%s-%s]未更新"),
    DATA_NOT_DELETED(213, "数据未删除", "数据[%s-%s]未删除"),
    DATA_NOT_FOUND(214, "数据未找到", "[%s-%s]数据未找到"),;


    private final static Map<Integer, ResponseCode> BY_CODE_MAP = Arrays.stream(ResponseCode.values())
            .collect(Collectors.toMap(ResponseCode::code, code -> code));

    private final int code;
    private final String desc;
    private final String template;


    ResponseCode(int code, String desc) {
        this.code = code;
        this.desc = desc;
        this.template = "";
    }

    ResponseCode(int code, String desc, String template) {
        this.code = code;
        this.desc = desc;
        this.template = template;
    }

    public int code() {
        return this.code;
    }

    public String desc() {
        return this.desc;
    }

    public String template() {
        return this.template;
    }

    /**
     * @param code 代码
     * @return 转换出来的状态码
     */
    public static ResponseCode parse(Integer code) {
        return BY_CODE_MAP.getOrDefault(code, ResponseCode.SYSTEM_ERROR);
    }
}
